package org.onvivals.app.mqtt.handler;

import cn.hutool.core.convert.Convert;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.iot.mqtt.core.server.auth.IMqttServerAuthHandler;
import org.onvivals.module.iot.service.IIotDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.tio.core.ChannelContext;

@Slf4j
@Configuration(proxyBeanMethods = false)
public class MqttAuthHandler implements IMqttServerAuthHandler {

    @Autowired
    private IIotDeviceService deviceService;

    @Override
    public boolean authenticate(ChannelContext context, String uniqueId, String clientId, String userName, String password) {
        // 客户端认证逻辑实现
        // 设备端认证
        String[] clientArray = clientId.split("&");
        if (clientArray.length != 3 || clientArray[0].equals("") || clientArray[1].equals("") || clientArray[2].equals("")) {
            log.error("设备mqtt客户端Id格式应为： 用户ID & 设备编号 & 激活码");
            return false;
        }
		//用户ID
        Long userId = Long.valueOf(clientArray[0]);
		//设备码
        String deviceNumber = Convert.toStr(clientArray[1]);
		//激活码
		String code = Convert.toStr(clientArray[2]);
        // 设备认证后自动添加设备
		return deviceService.insertDeviceAuto(deviceNumber, userId,code,null);
    }

}
